import { logout } from '@/store/action/login'
import { getUserProfile, updataPhoto, updataUser } from '@/store/action/profile'
// import { RootState } from '@/types/store'
import { useInitialState } from '@/utils/hooks'
import {
  Button,
  List,
  DatePicker,
  NavBar,
  Popup,
  Toast,
  Dialog,
} from 'antd-mobile'
import classNames from 'classnames'
import dayjs from 'dayjs'
import { useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router'
import EditInput from './EditInput'
import EditList from './EditList'
// import { useEffect } from 'react'
// import { useDispatch, useSelector } from 'react-redux'

import styles from './index.module.scss'

const Item = List.Item
type InputState = {
  type: '' | 'name' | 'intro'
  visible: boolean
}
type ListType = {
  type: '' | 'gender' | 'photo'
  visible: boolean
}

const ProfileEdit = () => {
  const [showInput, setShowInput] = useState<InputState>({
    type: '',
    visible: false,
  })

  const [showList, setShowList] = useState<ListType>({
    type: '',
    visible: false,
  })
  const profile = useInitialState(getUserProfile, 'profile').userProfile
  const dispatch = useDispatch()
  const history = useHistory()

  const hideInput = () => {
    setShowInput({
      type: '',
      visible: false,
    })
  }
  const hideList = () => {
    setShowList({
      type: '',
      visible: false,
    })
  }
  const fileRef = useRef<HTMLInputElement>(null)
  const onUpdata = async (key: string, value: string) => {
    if (key === 'photo') {
      fileRef.current!.click()
      return
    }
    // console.log(key, value)
    await dispatch(updataUser(key, value))
    hideInput()
    hideList()
    Toast.show({
      icon: 'success',
      content: '修改成功',
    })
  }
  const changePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files![0]
    const fd = new FormData()
    fd.append('photo', file)
    await dispatch(updataPhoto(fd))
    Toast.show({
      icon: 'success',
      content: '修改头像成功',
    })
    hideList()
  }
  const [showBirthday, setShowBirthday] = useState(false)
  const logoutFn = () => {
    Dialog.show({
      title: '温馨提示',
      content: '你确定要退出吗?',
      closeOnAction: true,
      actions: [
        [
          {
            key: 'cancel',
            text: '取消',
            style: {
              color: 'blue',
              fontSize: 20,
            },
          },
          {
            key: 'confirm',
            text: '确定',
            danger: true,
            style: {
              fontSize: 20,
            },
            onClick: () => {
              dispatch(logout())
              history.push('/login')
              Toast.show({
                icon: 'success',
                content: '退出成功',
              })
            },
          },
        ],
      ],
    })
  }
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          onBack={() => history.goBack()}
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img width={24} height={24} src={profile.photo} alt="" />
                </span>
              }
              arrow
              onClick={() =>
                setShowList({
                  type: 'photo',
                  visible: true,
                })
              }
            >
              头像
            </Item>
            <Item
              arrow
              extra={profile.name}
              onClick={() =>
                setShowInput({
                  type: 'name',
                  visible: true,
                })
              }
            >
              昵称
            </Item>
            <Item
              arrow
              extra={
                <span
                  className={classNames('intro', profile.intro && 'normal')}
                >
                  {profile.intro || '未填写'}
                </span>
              }
              onClick={() =>
                setShowInput({
                  type: 'intro',
                  visible: true,
                })
              }
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() =>
                setShowList({
                  type: 'gender',
                  visible: true,
                })
              }
            >
              性别
            </Item>
            <Item
              arrow
              extra={profile.birthday}
              onClick={() => setShowBirthday(true)}
            >
              生日
            </Item>
          </List>

          <DatePicker
            visible={false}
            value={new Date()}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={logoutFn}>
            退出登录
          </Button>
        </div>
      </div>
      {/* 修改昵称和简介 */}
      <Popup visible={showInput.visible} position="right" destroyOnClose>
        <EditInput
          hideInput={hideInput}
          type={showInput.type}
          onUpdata={onUpdata}
        ></EditInput>
      </Popup>
      {/* 修改性别和头像 */}
      <Popup visible={showList.visible} destroyOnClose onMaskClick={hideList}>
        <EditList
          hideList={hideList}
          type={showList.type}
          onUpdata={onUpdata}
        ></EditList>
      </Popup>
      {/* 修改头像 */}
      <input type="file" hidden ref={fileRef} onChange={changePhoto} />
      <DatePicker
        visible={showBirthday}
        value={new Date(profile.birthday)}
        onCancel={() => setShowBirthday(false)}
        onClose={() => {
          setShowBirthday(false)
        }}
        title="选择年月日"
        min={new Date('1900-01-01')}
        max={new Date()}
        onConfirm={(val) => {
          onUpdata('birthday', dayjs(val).format('YYYY-MM-DD'))
        }}
      />
    </div>
  )
}

export default ProfileEdit
